<template>
  <div class="dialog-content">
    <div class="title">
      <span>{{$t(phoneVerify ? 'set.closeloginwidthtel' : 'set.loginWithTel')}}</span>
    </div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
      <el-form-item class="mb0" prop="tel">
        <el-input v-model="ruleForm.tel" readonly :placeholder="$t('set.input_tel')"></el-input>
      </el-form-item>
      <small class="info">{{$t('set.binding_tel')}}</small>
      <div class="row">
        <el-form-item prop="code">
          <el-input v-model="ruleForm.code" :placeholder="$t('login.phone_code_input')"></el-input>
        </el-form-item>
        <el-button class="code-btn" type="primary" size="mini" round @click="getcode('set_login_code')" :disabled="!code.v_code_btn">{{code.codeStr}}</el-button>
      </div>
      <div class="dialog-footer">
        <el-button type="primary" round @click="submit">{{$t('btn.confirm')}}</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { setPhoneVerify, sendTelCode } from '@/api';
import { mapGetters, mapMutations } from 'vuex';

export default {
  data() {
    const validateCode = (rule, value, callback) => {
      const reg = /^\d{6}$/;
      if (!value.trim()) {
        callback(new Error(this.$t('forget.email_code_info')));
      } else if (!reg.test(value.trim())) {
        callback(new Error(this.$t('set.email_sure')));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        tel: '',
        code: '',
      },
      rules: {
        tel: [
          {
            required: true,
            message: this.$t('set.pinput_tel'),
            trigger: 'change',
          },
        ],
        code: [{ validator: validateCode, trigger: 'change' }],
      },
      code: {
        v_code_btn: true,
        codeStr: this.$t('btn.sendcode.sendcode'),
        time: 60,
        timer: null,
      },
    };
  },
  computed: {
    ...mapGetters(['phoneVerify', 'tel']),
    verify() {
      return this.phoneVerify ? 0 : 1;
    },
  },
  created() {
    this.ruleForm.tel = this.tel;
  },
  beforeDestroy() {
    window.clearInterval(this.code.timer);
  },
  methods: {
    ...mapMutations(['SET_PHONE_VERIFY']),
    getcode(type) {
      this.$refs.ruleForm.validateField('tel', (err) => {
        if (err) return;
        this.code.v_code_btn = false;
        this.code.codeStr = `${this.$t('btn.sendcode.resend')}(60s)`;
        clearInterval(this.code.timer);
        this.code.timer = setInterval(() => {
          if (this.code.time > 0) {
            this.code.time -= 1;
            this.code.codeStr = `${this.$t('btn.sendcode.resend')}(${this.code.time}s)`;
          } else {
            clearInterval(this.code.timer);
            this.code.time = 60;
            this.code.codeStr = this.$t('btn.sendcode.sendcode');
            this.code.v_code_btn = true;
          }
        }, 1000);
        sendTelCode({
          tel: this.ruleForm.tel,
          type,
        }).then((res) => {
          if (res.data.status === '1') {
            this.$notify({
              message: this.$t('set.sendcode'),
              type: 'success',
              duration: 2000,
              showClose: false,
            });
          } else {
            this.$message({
              message: this.$t(`api.${res.data.errcode}`),
              type: 'warning',
            });
          }
        }).catch(() => {
          this.$message.error(this.$t('error.catchError'));
        });
      });
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          setPhoneVerify({
            code: this.ruleForm.code,
            verify: this.verify,
          }).then((res) => {
            if (res.data.status === 1) {
              this.$notify({
                message: this.$t('api.6031'),
                type: 'success',
                duration: 2000,
                showClose: false,
              });
              this.SET_PHONE_VERIFY(this.verify);
              this.$emit('toggleDialog', { showDialog: false });
            } else {
              this.$message({
                message: this.$t(`api.${res.data.errcode}`),
                type: 'warning',
              });
            }
          }).catch(() => {
            this.$message.error(this.$t('error.catchError'));
          });
        }
      });
    },
  },
};
</script>
